package com.changyue.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


import com.changyue.MyApplication;
import com.changyue.greendao.gen.DaoMaster;
import com.changyue.greendao.gen.DaoSession;
import com.changyue.temp.BuildConfig;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 * 创建数据库、创建数据库表、包含增删改查的操作
 */

public class DaoManager {
    private static final String TAG = DaoManager.class.getName();
    private static final String DB_NAME = "RECORD_DB";

    private Context mContext;

    //多线程中要被共享的使用volatile关键字修饰
    private volatile static DaoManager manager = new DaoManager();
    private DaoMaster mDaoMaster;
    private DaoMaster.DevOpenHelper mHelper;
    private DaoSession mDaoSession;

    /**
     * 单例模式获得操作数据库对象
     */
    public static DaoManager getInstance() {
        if (manager == null) {
            manager = new DaoManager();
        }
        return manager;
    }

    public void init(Context context) {
        this.mContext = context;
    }

    /**
     * 判断是否有存在数据库，如果没有则创建
     */
    public DaoMaster getDaoMaster() {
        if (mDaoMaster == null) {
            if (mContext == null) {
                mContext = MyApplication.getInstance().getApplicationContext();
            }
            TrainOpenHelper helper = new TrainOpenHelper(mContext, DB_NAME, null);
            SQLiteDatabase db = helper.getWritableDatabase();
            mDaoMaster = new DaoMaster(db);
            Log.d("DaoMaster", "db path " + db.getPath());

        }
        setDebug();
        return mDaoMaster;
    }

    /**
     * 完成对数据库的添加、删除、修改、查询操作，仅仅是一个接口
     */
    public DaoSession getDaoSession() {
        if (mDaoSession == null) {
            if (mDaoMaster == null) {
                mDaoMaster = getDaoMaster();
            }
            mDaoSession = mDaoMaster.newSession();
        }
        return mDaoSession;
    }

    /**
     * 打开输出日志，默认关闭
     */
    public void setDebug() {
        if (BuildConfig.DEBUG) {
            QueryBuilder.LOG_SQL = true;
            QueryBuilder.LOG_VALUES = true;
        }
    }

    /**
     * 关闭所有的操作，数据库开启后，使用完毕要关闭
     */
    public void closeConnection() {
        closeHelper();
        closeDaoSession();
    }

    public void closeHelper() {
        if (mHelper != null) {
            mHelper.close();
            mHelper = null;
        }
    }

    public void closeDaoSession() {
        if (mDaoSession != null) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }
}